package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"warehouse/houserpc/houserpcclient"
	"warehouse/houserpc/internal/svc"
	"warehouse/model/mysql"
	"warehouse/model/redis"

	"warehouse/houserpc/houserpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *houserpc.ListRequest) (*houserpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page

	size := in.Size
	var count int64

	query := mysql.DB.Model(&mysql.Warehouse{})

	query.Count(&count)
	if in.Name != "" {
		query = query.Where("name like ?", "%"+in.Name+"%")
	}

	offset := (page - 1) * size
	var houses []mysql.Warehouse
	get, _ := redis.Client.Get("list" + strconv.FormatInt(offset, 10)).Result()
	if get == "" {
		query.Offset(int(offset)).Order("price desc").Limit(int(size)).Find(&houses)
		marshal, _ := json.Marshal(&houses)
		redis.Client.Set("list"+strconv.FormatInt(offset, 10), marshal, time.Minute*5)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get), &houses)
		fmt.Println("redis")
	}

	var lists []*houserpcclient.HouseList
	for _, m := range houses {
		list := houserpcclient.HouseList{
			Id:        int64(m.ID),
			Num:       m.Num,
			Types:     m.Types,
			Name:      m.Name,
			CreatedAt: m.CreatedAt.Format(time.DateTime),
			UpdatedAt: m.UpdatedAt.Format(time.DateTime),
			Quantity:  int64(m.Quantity),
			Price:     float32(m.Price),
			User:      m.User,
		}
		lists = append(lists, &list)
	}
	return &houserpc.ListResponse{List: lists, Count: count}, nil
}
